<?php
namespace app\parent;
use think\Controller;
use think\Db;
use think\facade\Session;

class parents extends Controller
{
    protected $beforeActionList = [
        'first',
    ];

    public $wid = '';
    
    protected function first()
    {

        if(request()->has('agencyrankid','get')){
            session('agencyrankid',request()->param('agencyrankid'));
        }
        if(request()->has('agencyrankkey','get')){
            $this->isRank(request()->param('agencyrankkey'));
        }
        
        $login_arr = ['index/login','index/accredit'];
        if(!in_array($this->request->path(),$login_arr)){
            if(Session::has('wid')){
                $admin_id = Session::get('wid');
                $wid_type = Session::get('wid_type');
                if($admin_id > 0){

                    $dbs = $wid_type ? 'agency_user' : 'agency_number';
                    $admin_is = Db::name($dbs)->where('id',$admin_id)->value('id');
                    if(!$admin_is){
                        redirect('/index.php/index/login');
                    }
                }else{
                    redirect('/index.php/index/login');
                }
            }else{
                redirect('/index.php/index/login');
            }
        }
        $this->wid = $this->session('wid');
    }

    public $request;
    public $session;

	public function _initialize()
    {
        // ->fetchSql(true)
        $this->request  =   request();

    }

    // json 返回
    public function ajaxReturn($code = '',$msg = '',$data = '',$count = 0)
    {
        echo json_encode(['code'=>$code,'msg'=>$msg,'data'=>$data,'count'=>$count]);die;
    }

    public function isRank($key = '')
    {
        if(!$key){
            return '';
        }
        $id = session('agencyrankid');
        $admin_rank_content = session('agency_rank_content');
        // agencyrankkey
        $isrank = true;
        if($admin_rank_content && isset($admin_rank_content[$id]) && isset($admin_rank_content[$id][$key])){
            $isrank = false;
            if($key != 'title'){
                $this->setLog($admin_rank_content[$id]['title'],'执行了-【'.$admin_rank_content[$id][$key].'】-操作，在-【'.$admin_rank_content[$id]['title'].'】');
            }
        }

        if($isrank){
            if($this->isAjax()){
                $this->ajaxReturn(1,'您没有当前操作权限！');
            }else{
                back('您没有当前操作权限！');
            }
            die;  
        }
    }

    /**
    * showdoc
    * 操作日志
    * event  事件类型
    * content  事件内容
    */
    public function setLog($event = '',$content = '')
    {
        \think\Db::name('agency_log')->insert([
            'agency_log_p_id'  => session('wid'),
            'agency_log_p_nickname'  => session('wid_nickname'),
            'agency_log_nickname'  => session('agency_nickname'),
            'agency_log_rank_name'  => session('agency_rank_title'),
            'agency_log_ip'  => session('agency_x_ip'),
            'agency_log_event'  => $event,
            'agency_log_content'  => $content,
            'agency_log_is_show'  => 1,
            'agency_log_times'  => time(),
        ]);
    }

    
    /**
    * showdoc
    * 组成列表页查询条件
    * like , time , eq = 三个条件类型
    * ['like' => ['key1','key2']]
    */
    public function whereSql($arr)
    {
        $where = [];
        $info = $this->input();

        if(isset($arr['eq']) && is_array($arr['eq'])){

            foreach($arr['eq'] as $v){
                if(isset($info[$v]) && $info[$v] != ''){
                    $where[] = $v . '=' . $info[$v];
                }
            }

        }
        
        if(isset($arr['like']) && is_array($arr['like'])){
            
            foreach($arr['like'] as $v){
                if(isset($info[$v]) && $info[$v] != ''){
                    $where[] = $v . " like '%{$info[$v]}%'";
                }
            }

        }
        
        if(isset($arr['time']) && is_array($arr['time'])){
            
            foreach($arr['time'] as $v){
                if(isset($info[$v]) && $info[$v] != ''){
                    $d = $this->whereSqlDate($info[$v]);
                    $where[] = "{$v} >= {$d[0]} and {$v} <= {$d[1]}";
                }
            }
        
        }

        if($where){
            $where = implode(' and ',$where);
        }else{
            $where = '';
        }

        return $where;
    }

    public function whereSqlDate($str = '')
    {
        $arr = explode('|',$str);

        $arr[0] = trim($arr[0]);
        $arr[0] = explode(' ',$arr[0]);

        $d1 = explode('-',$arr[0][0]);
        $d2 = explode(':',$arr[0][1]);

        $da[] =   mktime($d2[0],$d2[1],$d2[2],$d1[1],$d1[2],$d1[0]); 

        $arr[1] = trim($arr[1]);
        $arr[1] = explode(' ',$arr[1]);

        $b1 = explode('-',$arr[1][0]);
        $b2 = explode(':',$arr[1][1]);
        
        $da[] =   mktime($b2[0],$b2[1],$b2[2],$b1[1],$b1[2],$b1[0]);

        return $da;
    }

    public function dateTime($str = '')
    {
        $str = trim($str);
        $str = explode(' ',$str);

        $d1 = explode('-',$str[0]);

        if(isset($str[1])){
            $d2 = explode(':',$str[1]);
        }else{
            $d2 = [0,0,0];
        }

        $da =   mktime($d2[0],$d2[1],$d2[2],$d1[1],$d1[2],$d1[0]); 

        return $da;
    }

    // 是否为Post访问
    public function isPost()
    {
        return $this->request->isPost();
    }

    // 是否为Get访问
    public function isGet()
    {
        return $this->request->isGet();
    }

    // 是否为Ajax访问
    public function isAjax()
    {
        return $this->request->isAjax();
    }

    // 是否为手机访问
    public function isMobile()
    {
        return $this->request->isMobile();
    }


    // 获取哪些请求参数
    public function input($data = '',$redata = false)
    {

        if($data){
            if(is_array($data)){
                $arr = [];
                $param = $this->request->param();
                foreach ($data as $key => $value) {

                    if(isset($param[$value])){
                        $arr[$value] = $param[$value];
                    }else{
                        if($redata !== false){
                            $arr[$value] = $redata;
                        }
                    }

                }
                return $arr;
            }else{

                $arr = $redata;
                $param = $this->request->param();
                foreach ($param as $key => $value) {

                    if($key == $data){
                        $arr = $value;
                    }

                }

                return $arr;
            }
        }else{
            $param = $this->request->param();
            if(isset($param['agencyrankid'])){
                unset($param['agencyrankid']);
            }

            if(isset($param['agencyrankkey'])){
                unset($param['agencyrankkey']);
            }
            return $param;
        } 
    }
     
    // 获取哪些请求参数
    public function unInput($data = '')
    {
        if($data){
            if(is_array($data)){
                
                $data[] = 'agencyrankid';
                $data[] = 'agencyrankkey';
                
                $param = $this->request->param();
                foreach ($param as $key => $value) {
                    if(in_array($key,$data)){
                        unset($param[$key]);
                    }
                }
                return $param;
            
            }else{
                $param = $this->request->param();

                if(isset($param[$data])){
                    unset($param[$data]);
                }

                if(isset($param['agencyrankid'])){
                    unset($param['agencyrankid']);
                }
    
                if(isset($param['agencyrankkey'])){
                    unset($param['agencyrankkey']);
                }

                return $param;
            }
        }else{
            $param = $this->request->param();
            if(isset($param['agencyrankid'])){
                unset($param['agencyrankid']);
            }

            if(isset($param['agencyrankkey'])){
                unset($param['agencyrankkey']);
            }
            return $param;
        }
    }

    public function session($data = '',$reData = '')
    {
        if(is_array($data) && $data){

            $arr = [];
            foreach ($data as $k => $v) {
                if(Session::has($v)){
                    $arr[$v] = Session::get($v);
                }else{
                    $arr[$v] = $reData;
                }
            }
            return $arr;

        }else if($data){

            if(Session::has($data)){
                return Session::get($data);
            }else{
                return $reData;
            }

        }else{

            return $reData;

        }
    }

    public function sessionSet($data = '',$reData = '')
    {
        if($data){
            if(is_array($data)){
                foreach ($data as $key => $value) {
                    Session::set($key,$value);
                }
            }else{
                Session::set($data,$reData);
            }
        }

        return '';
    }

    // 验证 $rule = 匹配规则 $msg = 提示信息 $data = 参与匹配得数据
    public function mate($rule = '', $msg = '', $data = '')
    {
        /*
            // 表示验证name字段的值是否在user表（不包含前缀）中唯一
            'name'   => 'unique:user',
            // 验证其他字段
            'name'   => 'unique:user,account',
            // 排除某个主键值
            'name'   => 'unique:user,account,10',
            // 指定某个主键值排除
            'name'   => 'unique:user,account,10,user_id',
         */
        $validate = new \think\Validate($rule,$msg);

        $data = $data ? $data : $this->input() ;
        
        $validate->check($data);
        $err = $validate->getError();
        if($err){
            \think\Session::set('Tmsg',$err);
            echo '<script>self.location=document.referrer;</script>';
            exit;
        }

        return true;
    }

    /**
     * [验证方法]
     * @param  [array] $rule array(验证规则,规则返回,[参数数组])
     * @param  [array] $info array(表名,条件,参数) | array(table=>表名,where=>条件,info=>参数)
     * @param  [string | int] $is Add | 1    Up | 0
     * @return 无
     */
    public function rturnMate($table = 0, $info = [], $rule = [], $function = false)
    {
        $rule_is = true;
        $way     = '';
        if(isset($rule[0]) && $rule[0]){
            if(isset($rule[2])){
                $rule_is = $this->mate($rule[0], $rule[1], $rule[2]);
            }else{
                $rule_is = $this->mate($rule[0], $rule[1]);
            }
        }

        if(isset($info['id'])){
            $id = $info['id'];
            unset($info['id']);
        }else{
            $id = 0;
        }

        $iss = $id == 0 ? -3 : -2 ;

        $urlPath = '/'.substr($this->request->path(),0,$iss).urlText(true);
        if($rule_is){

            if($id == 0){
                $info[$table.'_times'] = time();
                $is_db = Db::name($table)->insertGetId($info);
                $id = $is_db;
            }else{

                $is_db = Db::name($table)->where($table.'_id',$id)->update($info);
            }

            if($is_db || $way != false){
                if($way != false){
                    $info['id'] = $id;
                    $way($table,$info);
                }

                $up = '';
                if($id == 0){
                    $up = '添加';
                }else{
                    $up = '修改';
                }

                if(\think\Session::has('column_name_rank')){
                    $column_name_rank = \think\Session::get('column_name_rank');
                    operation_log('在 ['.$column_name_rank.'] 执行了{ '.$up.' }操作');
                }

                return redirect($urlPath,'存储成功',0);
            }else{
                return back('存储失败');
            }

        }else{
            return back('验证失败');
        }

    }

}
